<?php

class SummaryController extends Controller
{
    public $layout = '//layouts/main';
    public $defaultAction = 'view';


    public function actionView()
    {
        session_write_close();
        $this->render('view');
    }

    public function actionAjaxGetChart()
    {
        session_write_close();
        if (Yii::app()->request->isPostRequest) {
            $res = array('code' => '', 'msg' => '', 'data' => array());
            //当前时间
            $ts = MsggSummary::getMinuteBase();
            $type = $this->getQuery('post', 'type');

            //截止日期
            $end = $this->getQuery('post', 'end', $ts);
            //查询开始
            $start = $this->getQuery('post', 'start', MsggSummary::getDayBase($end));
            if ($start > $end) {
                $start = $end - 86400;
            }
            switch ($type) {
                case 'summary_output':
                case 'summary_input':
                    $start = MsggSummary::getMinuteBase($start);
                    $end = MsggSummary::getMinuteBase($end);
                    $dataZoomX = array('type' => 'inside', 'start' => 90, 'end' => 100);
                    $series = array();
                    $legendData = array();
                    $xAxisData = array();
                    $series_item = array(
                        'name' => '',
                        'type' => 'line',
                        'stack' => 'item',
                        'areaStyle' => array('normal' => []),
                        'data' => array());
                    $details = explode('_', 2);
                    $direction = $details[1];
                    $target = $direction == 'input' ? 'item' : 'log';
                    $title = MsggSummary::getOptions('view_type')[$type];
                    $summary_data = MsggSummary::model()->findAll('`target`=:target and `ts`>=:start and `ts`<=:end', [':target' => $target, ':start' => $start, ':end' => $end]);
                    $types = array(MsggItem::TYPE_CALL, MsggItem::TYPE_SMS, MsggItem::TYPE_WECHAT, MsggItem::TYPE_MAIL);
                    $sums = array();
                    //foeache data
                    array_walk($summary_data, function ($val) use (&$types, &$sums) {
                        $type = $val->type;
                        !in_array($type, $types) && ($types[] = $type);
                        $time = $val->ts;
                        if (!isset($sums[$time])) {
                            $sums[$time] = array();
                        }
                        if (!isset($sums[$time][$type])) {
                            $sums[$time][$type] = ['sum' => 0];
                        }
                        if (!isset($sums[$time][$type][$val->status])) {
                            $sums[$time][$type][$val->status] = 0;
                        }
                        $sums[$time][$type]['sum'] += $val->sum;
                        $sums[$time][$type][$val->status] += $val->sum;
                    });

                    //gen
                    for ($i = $start; $i <= $end; $i += MsggSummary::DURATION_MINUTE) {
                        $xAxisData[] = date('y-m-d H:i', $i);
                    }
                    foreach ($types as $type) {
                        $legendData[] = $type;
                        $series_item['name'] = $type;
                        $series_item['data'] = [];
                        $series_item['label'] = [];
                        for ($i = $start; $i <= $end; $i += MsggSummary::DURATION_MINUTE) {
                            $series_item['data'][] = isset($sums[$i][$type]['sum']) ? $sums[$i][$type]['sum'] : 0;
                        }
                        $series_item['label'] = array('normal' => ['show' => true, 'position' => 'top']);
                        $series[] = $series_item;
                    }
                    //gen option
                    $option = $this->getStackedAreaCharts(array(
                        'title' => $title,
                        'legendData' => $legendData,
                        'xAxisData' => $xAxisData,
                        'series' => $series,
                        'dataZoomX' => $dataZoomX));
                    $res['data'] = $option;
                    break;
                case 'summary_output_mail_detail':
                case 'summary_input_mail_detail':
                case 'summary_output_call_detail':
                case 'summary_input_call_detail':
                case 'summary_output_wechat_detail':
                case 'summary_input_wechat_detail':
                case 'summary_output_sms_detail':
                case 'summary_input_sms_detail':
                    $start = MsggSummary::getMinuteBase($start);
                    $end = MsggSummary::getMinuteBase($end);
                    $title = MsggSummary::getOptions('view_type')[$type];
                    $details = explode('_', $type, 4);
                    $direction = $details[1];
                    $type = $details[2];
                    $target = $direction == 'input' ? 'item' : 'log';

                    $dataZoomX = array('type' => 'inside', 'start' => 90, 'end' => 100);
                    $series = array();
                    $legendData = array();
                    $xAxisData = array();
                    $series_item = array(
                        'name' => '',
                        'type' => 'line',
                        'stack' => 'item',
                        'areaStyle' => array('normal' => []),
                        'data' => array());

                    $summary_data = MsggSummary::model()->findAll('`target`=:target and `type`=:type and `ts`>=:start and `ts`<=:end', [':target' => $target, ':type' => $type, ':start' => $start, ':end' => $end]);

                    $status = array();
                    $sums = array();
                    //foeache data
                    array_walk($summary_data, function ($val) use (&$status, &$sums) {
                        $mapStatus = MsggItem::getOptions('status')[$val->status];
                        !in_array($mapStatus, $status) && ($status[] = $mapStatus);
                        $time = $val->ts;
                        if (!isset($sums[$time])) {
                            $sums[$time] = array();
                        }
                        if (!isset($sums[$time][$mapStatus])) {
                            $sums[$time][$mapStatus] = 0;
                        }
                        $sums[$time][$mapStatus] += $val->sum;
                    });

                    //gen
                    for ($i = $start; $i <= $end; $i += MsggSummary::DURATION_MINUTE) {
                        $xAxisData[] = date('y-m-d H:i', $i);
                    }
                    foreach ($status as $s) {
                        $legendData[] = $s;
                        $series_item['name'] = $s;
                        $series_item['data'] = [];
                        $series_item['label'] = [];
                        for ($i = $start; $i <= $end; $i += MsggSummary::DURATION_MINUTE) {
                            $series_item['data'][] = isset($sums[$i][$s]) ? $sums[$i][$s] : 0;
                        }
                        $series_item['label'] = array('normal' => ['show' => true, 'position' => 'top']);
                        $series[] = $series_item;
                    }
                    //gen option
                    $option = $this->getStackedAreaCharts(array(
                        'title' => $title,
                        'legendData' => $legendData,
                        'xAxisData' => $xAxisData,
                        'series' => $series,
                        'dataZoomX' => $dataZoomX));
                    $res['data'] = $option;
                    break;
                default:
                    $res['code'] = 1;
                    $res['msg'] = 'Unknown Chart';
                    break;
            }
            echo json_encode($res);
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    //堆叠面积图
    private static function getStackedAreaCharts($params)
    {
        $title = empty($params['title']) ? '' : $params['title'];
        $legendData = (empty($params['legendData']) || !is_array($params['legendData'])) ? [] : $params['legendData'];
        $xAxisData = (empty($params['xAxisData']) || !is_array($params['xAxisData'])) ? [] : $params['xAxisData'];
        $series = (empty($params['series']) || !is_array($params['series'])) ? [] : $params['series'];
        $dataZoomX = (empty($params['dataZoomX']) || !is_array($params['dataZoomX'])) ? [] : $params['dataZoomX'];
        $option = [
            "title" => array('text' => $title),
            "tooltip" => array('trigger' => 'axis'),
            "legend" => array('data' => $legendData),
            "toolbox" => array('feature' => array("saveAsImage" => [], 'dataZoom' => array('yAxisIndex' => 'none'), 'restore' => [],)),
            'grid' => array('left' => '3%', 'right' => '4%', 'bottom' => '13%', 'containLabel' => true),
            'xAxis' => array(['type' => 'category', 'boundaryGap' => false, 'data' => $xAxisData,]),
            'yAxis' => array(['type' => 'value', "scale" => false]),
            'dataZoom' => array($dataZoomX, ['show' => true, 'type' => 'slider', 'y' => '90%', 'start' => 20, 'end' => 100]),
            'series' => $series
        ];


        return $option;
    }


}